#include <iostream>
#include <cv.h>
#include <highgui.h>

using namespace std;
using namespace cv;

float complexity(Mat src) {
    Mat outline;
    int ink = countNonZero(src);

    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;

    Mat temp;
    src.convertTo(temp, CV_8UC1);
    findContours(temp, contours, hierarchy, CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE);

    float perimeter = 0;
    for (int i=0; i < contours.size(); i++) {
      // contour without parents only, otherwise
      // we double count holes
      if (hierarchy[i][3] < 0)
        perimeter += arcLength(contours[i], true);
    }

//    dilate(src, outline, Mat());
//    outline = outline - src;
//    dilate(outline, outline, Mat());
//    int perimeter = countNonZero(outline) / 3;
    return ((float)perimeter*perimeter / ink);
}

//int main(int argc, char* argv[]) {
//    Mat image;
//
//    image = imread( argv[1], CV_LOAD_IMAGE_GRAYSCALE );
//    threshold(image, image, 100, 255, THRESH_BINARY);
//
//    cout << complexity(image) << endl;
//}
